package com.example.restful01.controller;

import com.example.restful01.model.Book;
import com.example.restful01.service.BookService;
import com.example.restful01.service.impl.BookServiceImpl;
import com.example.restful01.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api") // 与前端axios的baseURL对应
@CrossOrigin // 跨域注解，也可以使用上面的全局配置
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private BookServiceImpl bookServiceImpl;

    // 书籍列表接口
    @GetMapping("/books")
    public Result initBooksList() {
        return Result.success(bookService.list());
    }

    // 添加书籍接口
    @PostMapping("/adminaddbooks")
    public Result addBooks(@RequestBody Book book) {
        boolean isSuccess = bookService.save(book);
        if (isSuccess) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }
    @GetMapping("/searchbook")
    public Result searchBook(@RequestParam String name) {
        if(!bookService.searchBook(name).isEmpty()){
            return Result.success(bookService.searchBook(name));
        }else{
            return Result.error("没有数据！");
        }
    }
    @DeleteMapping("/delbook")
    public Result delBook(@RequestParam Integer id) {
        if (bookService.removeById(id)) {
            return Result.success("删除书籍成功！");
        } else return Result.error("删除书籍失败！");
    }
//    @PutMapping("changebookinfo")
//    public Result changeBookInfo(@RequestBody Book book) {
//        if(bookService.changeBookInfo(book)){
//            return Result.success("修改成功！");
//        }else{
//            return Result.error("修改失败！");
//        }
//    }
@PutMapping("/changebookinfo/{id}")
public ResponseEntity<?> updateBookInfo(@PathVariable Integer id, @RequestBody BookUpdateRequest request) {
    try {
        // 调用服务层方法更新书籍信息
        Book updatedBook = bookServiceImpl.updateBookInfo(id, request.getField(), request.getValue());
        return ResponseEntity.ok().body(Result.success("修改成功！")); // 返回更新后的书籍信息
    } catch (RuntimeException e) {
        return ResponseEntity.badRequest().body(Result.error(e.getMessage())); // 返回错误信息
    }
}
}

// 数据传输对象，用于接收前端传递的字段和值
class BookUpdateRequest {
    private String field; // 字段名
    private String value; // 字段值

    // Getter 和 Setter 方法
    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    // 其他接口...
}